package net.sf.midollo.net.http.text;

import net.sf.midollo.io.text.Formatter;

import java.io.IOException;

public class HttpFormatter {

	protected final Formatter formatter;

	public HttpFormatter(Formatter formatter) throws IOException {
		this.formatter = formatter;
	}

	public void formatRequestLine(String method, String uri, int majorVer, int minorVer) throws IOException {
		this.formatter.formatString(method + ' ' + uri + " HTTP/" + majorVer + '.' + minorVer);
		this.formatter.formatCRLF();
	}

	public void formatResponseLine(int majorVer, int minorVer, int statusCode, String statusDesc) throws IOException {
		this.formatter.formatString("HTTP/" + majorVer + '.' + minorVer + ' ' + statusCode + ' ' + statusDesc);
		this.formatter.formatCRLF();
	}

	public void formatHeaderLine(String headerName, String headerValue) throws IOException {
		formatHeaderName(headerName);
		formatHeaderValue(headerValue);
	}

	public void formatHeaderLine(String headerName, long headerValue) throws IOException {
		formatHeaderName(headerName);
		formatHeaderValue(headerValue);
	}

	public void formatHeaderName(String headerName) throws IOException {
		this.formatter.formatString(headerName + ": ");
	}

	public void formatHeaderValue(String headerValue) throws IOException {
		this.formatter.formatString(headerValue);
		this.formatter.formatCRLF();
	}

	public void formatHeaderValue(long headerValue) throws IOException {
		this.formatter.formatLong(headerValue);
		this.formatter.formatCRLF();
	}

	public void formatHeaderConnectionKeepAlive() throws IOException {
		formatHeaderLine("Connection", "keep-alive");
	}

	public void formatHeaderContentLength(long contentLength) throws IOException {
		formatHeaderLine("Content-Length", contentLength);
	}
}
